﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using RemoteSpark.Resources;
using System.IO;
using System.Text;

namespace RemoteSpark
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }
        private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
        {
            DoOperation(ledRedSwitch, "l1");
        }
        private void GreenToggleSwitch_Toggled(object sender, RoutedEventArgs e)
        {
            DoOperation(ledGreenSwitch, "l2");
        }
        private async void DoOperation(ToggleSwitch toggle, string name)
        {
            toggle.IsEnabled = false;
            progressBar.IsIndeterminate = true;
            try
            {
                var result = await SparkIo.Set(name, toggle.IsChecked == true ? "HIGH" : "LOW");
                toggle.IsChecked = result.ok ? toggle.IsChecked : !toggle.IsChecked;
                responseTextblock.Text = result.error;
            }
            catch (AggregateException exs)
            {
                responseTextblock.Text = string.Empty;
                foreach (var ex in exs.InnerExceptions)
                {
                    responseTextblock.Text += ex.Message;
                }

            }
            toggle.IsEnabled = true;
            progressBar.IsIndeterminate = false;
        }
    
        private async void tempButton_Click(object sender, RoutedEventArgs e)
        {
            temperatureButton.IsEnabled = false;
            responseTextblock.Text = "Waiting response...";
            progressBar.IsIndeterminate = true;
            try
            {
                var result = await SparkIo.GetTemperature();
                temperatureTextBlock.Text = string.Format("{0}°", result.result);
                lastModifiedTextBlock.Text = string.Format("Last update at {0}", result.coreInfo.last_heard);
                responseTextblock.Text = string.Empty;
            }
            catch (AggregateException exs)
            {
                responseTextblock.Text = string.Empty;
                foreach(var ex in exs.InnerExceptions)
                {
                    responseTextblock.Text += ex.Message;
                }
            }
            temperatureButton.IsEnabled = true;
            progressBar.IsIndeterminate = false;
        }
      
    }
}